package com.audaque.springboot.foshanupload.email.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;

/**
 * @Author: yaobin
 * @Date: 2023/1/30 14:51
 */
@Slf4j
@Component
public class EmailProvider {
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;


    public void sendMimeMessage(String subject,
                                String content,
                                String[] to,
                                MultipartFile file,
                                String[] cc) throws MessagingException {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
        helper.setFrom(from); //设置发件人Email
        helper.setSubject(subject); //设置邮件主题


        //注意：Context 类是在org.thymeleaf.context.Context包下的。
        Context context = new Context();
        //html中填充动态属性值
        context.setVariable("from", from);
        context.setVariable("subject", subject);
        context.setVariable("content", content);
        //注意：process第一个参数名称要和templates下的模板名称一致。要不然会报错
        //org.thymeleaf.exceptions.TemplateInputException: Error resolving template [email]
        String htmlContent = templateEngine.process("email", context);



        //这里的 true，你加了的话，它发送你HTML页面里面的内容
        //不加的话，默认是 false，它发送整个HTML页面代码
        helper.setText(htmlContent, true);   //设置邮件主题内容
        //收件人集合
        helper.setTo(to);
        //抄送人集合
        if (ArrayUtils.isNotEmpty(cc)) {
            helper.setCc(cc);
        }
        //附件
        helper.addAttachment(file.getOriginalFilename(),file);


        javaMailSender.send(msg);

    }






}
